import React from 'react'
import ReactDOM from 'react-dom'
import './base.css'
// 兄弟间传值
export default class App extends React.Component {
  state = {
    list: [
      { id: 1, username: '叶树森', content: '冲冲冲冲冲冲冲冲冲冲' },
      { id: 2, username: '叶树森2', content: '冲冲冲冲冲冲冲冲冲冲' },
      { id: 3, username: '叶树森3', content: '冲冲冲冲冲冲冲冲冲冲' },
    ],
    username: '',
    content: '',
  }
  handDetele = (id) => {
    this.setState({ list: this.state.list.filter((item) => item.id !== id) })
  }
  handClear = () => {
    this.setState({ list: [] })
  }
  handleAdd = ({ username, content }) => {
    this.setState({ list: [{ id: Date.now(), username, content }, ...this.state.list] })
  }
  render() {
    return (
      <>
        <div className='app'>
          {/* 移动端推荐写法 */}
          <Myform list={this.state.list} handleClear={this.handClear} handleAdd={this.handleAdd} />
          <Mylist list={this.state.list} handleDetele={this.handDetele} />
        </div>
      </>
    )
  }
}

class Myform extends React.Component {
  state = {
    username: '',
    content: '',
  }
  handChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    })
  }
  handlePublish = (e) => {
    e.preventDefault()
    // console
    // this.state.username
    const { username, content } = this.state
    console.log(username, content)
    if (username.trim() === '' || content.trim() === '') return alert('不能为空')
    // this.setState({
    //   list: [...this.state.list, { id: Date.now(), username, content }],
    //   username: '',
    //   content: '',
    // })
    this.props.handleAdd({ username, content })
    this.setState({ username: '', content: '' })
  }
  render() {
    return (
      <>
        <form onSubmit={this.handlePublish}>
          <input onChange={this.handChange} value={this.state.username} type='text' className='user' placeholder='请输入评论人' name='username' />
          <br />
          <textarea onChange={this.handChange} value={this.state.content} name='content' id='' cols='30' rows='10' placeholder='请输入评论'></textarea>
          <br />
          <button>发表评论</button>
          <button type='button' onClick={this.props.handleClear}>
            清空评论
          </button>
        </form>
      </>
    )
  }
}
class Mylist extends React.Component {
  state = {
    username: '',
    content: '',
  }
  render() {
    return (
      <>
        {this.props.list.length === 0 ? (
          <div>暂无评论</div>
        ) : (
          <ul>
            {this.props.list.map((item) => (
              <li key={item.id}>
                <h3>评论人：{item.username}</h3>
                <p>评论内容：{item.content}</p>
                <button onClick={() => this.props.handleDetele(item.id)}>删除</button>
              </li>
            ))}
          </ul>
        )}
      </>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))
